/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-11-22 16:19:19
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-06-06 09:24:16
 * @FilePath: \cxl-driving-training\src\views\clueManagement\clue\index.ts
 */
import { BaseData, BaseMethod, expandInterface } from '@/utils/basc-data'
import { tableConfig } from './config'
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { clueEdit, clueListById, clueOperationInterface, cluePage, cluePageInterface, importClues } from '@/apis/clue'
import { CreateAxiosDownload } from '@/utils'
import { DICT_DATA } from '@/utils/dict-data'

export default class ClueListData extends BaseData implements BaseMethod {
    dialog = reactive({
        visible: false,
        title: '编辑',
        width: '800px',
        id: '',
        type: 'create'
    })
    dialogForm = reactive({
        remark: '',
        followStatus: '0',
        id: ''
    })
    followStatus = reactive<{ label: string; value: string }[]>([])
    activities = reactive<{ followMsg: string; followTime: string; follower: string }[]>([])
    searchData = {
        followStatus: '',
        dataSource: [],
        phone: '',
        customerName: '',
        referrer: '',
        time: [],
        customerType: '0',
        followerAssignStatus: '',
        transactionChannel: ''
    }
    syncDialog = reactive({
        visible: false,
        title: '同步数据',
        width: '600px',
        type: 'create'
    })
    defaultTime = reactive([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])
    syncDialogForm = reactive({
        type: '1',
        datetimerange: []
    })
    syncType = reactive<{ label: string; value: string }[]>([])
    syncRules = {
        datetimerange: [{ required: true, message: '请选择同步时间', trigger: 'change' }],
        type: [{ required: true, message: '请选择同步类型', trigger: 'change' }]
    }
    //详情弹窗
    detailData: any = reactive({})
    detailDialog = reactive({
        visible: false
    })
    detailDataPropName: any = reactive({
        customerId: '客户ID',
        customerName: '客户姓名',
        phone: '手机号码',
        viewedClassName: '查看班别',
        customerType: '客户类型',
        schoolName: '驾校',
        areaName: '区域',
        followerAssignStatus: '分配状态',
        dataSource: '数据来源',
        transactionChannel: '成交渠道',
        followStatus: '跟进状态',
        follower: '跟进人',
        createTime: '创建时间',
        lastViewedTime: '最后访问时间',
        signupTime: '报名时间',
        storeName: '报名门店',
        storeAreaName: '所属片区',
        referrerName: '分销人员姓名',
        referrerPhone: '分销人员手机号',
        signupOrderNo: '订单编号',
        lastFollowMsg: '最后跟进信息',
        updateTime: '更新时间'
    })
    //分配弹窗
    allocateDialog = reactive({
        visible: false
    })
    //存放选择表格数据
    multiSelectionData: any[] = reactive([])
    editDialog = reactive({
        visible: false,
        title: '新增数据',
        width: '600px',
        type: 'create'
    })
    constructor() {
        super(tableConfig)
        this.followStatus = DICT_DATA.get('followStatus')
        this.syncType = DICT_DATA.get('syncType')

        this.getData()

        console.log('table', this.pageData.table)
    }
    getData = (arg?: any) => {
        const params: cluePageInterface = {
            current: this.pageData.pagination.pageNo,
            size: this.pageData.pagination.pageSize
        }
        console.log('cluePageInterface', this.searchData)
        if (this.searchData.followStatus !== '' && this.searchData.followStatus !== '-1') {
            params.followStatus = Number(this.searchData.followStatus)
        }
        if (this.searchData.dataSource.length) {
            params.dataSources = this.searchData.dataSource.join(',')
        }
        if (this.searchData.phone !== '') {
            params.phone = this.searchData.phone + ''
        }
        if (this.searchData.customerName !== '') {
            params.customerName = this.searchData.customerName + ''
        }
        if (this.searchData.referrer !== '') {
            params.referrer = this.searchData.referrer + ''
        }
        if (this.searchData.customerType !== '') {
            params.customerType = Number(this.searchData.customerType)
        }
        if (this.searchData.followerAssignStatus !== '') {
            params.followerAssignStatus = Number(this.searchData.followerAssignStatus)
        }
        if (this.searchData.time.length) {
            params.startCreateTime = this.searchData.time[0]
            params.endCreateTime = this.searchData.time[1]
        }
        if (this.searchData.transactionChannel !== '') {
            params.transactionChannel = this.searchData.transactionChannel + ''
        }

        cluePage(params).then(res => {
            if (Number(res.data.code) === 200) {
                this.pageData.table.data.length = 0
                this.pageData.pagination.total = res.data.result.total

                const arr: any[] = res.data.result.records

                arr.forEach((element: any) => {
                    element.status = Number(element.disable) === 0 ? true : false
                    const name = element.referrerName || ''
                    const phone = element.referrerPhone || '' ? '(' + element.referrerPhone + ')' : ''
                    element.referrerStr = name + phone
                    const areaName = element.areaName
                    const cityName = element.cityName
                    if (cityName && areaName) {
                        element.area = cityName + '/' + areaName
                    } else if (cityName && !areaName) {
                        element.area = cityName
                    } else if (!cityName && areaName) {
                        element.area = areaName
                    }
                    this.pageData.table.data.push(element)
                })
            }
        })
    }
    onSearch = (arg?: any) => {
        console.log(arg)
        this.searchData = arg
        this.getData()
    }
    onReset = (arg?: any) => {
        this.searchData = {
            followStatus: '',
            dataSource: [],
            phone: '',
            customerName: '',
            referrer: '',
            time: [],
            customerType: '',
            followerAssignStatus: '',
            transactionChannel: ''
        }
        this.getData()
    }
    onPaginationChange = (arg?: any) => {
        this.pageData.pagination.pageNo = arg
        this.getData()
    }
    onPaginationSize = (arg?: any) => {
        this.pageData.pagination.pageNo = 1
        this.pageData.pagination.pageSize = arg
        this.getData()
    }
    onOperation = (arg?: any) => {
        const { type, data } = arg
        console.log(type, data)
        if (type === 'edit') {
            this.dialog.visible = true
            this.dialogForm.id = data.id
            this.dialogForm.remark = ''
            this.dialogForm.followStatus = data.followStatus + ''
            clueListById(data.id).then(res => {
                if (Number(res.data.code) === 200) {
                    this.activities.length = 0
                    this.activities.push(...res.data.result)
                }
            })
        } else if (type === 'download') {
            let url = import.meta.env.VITE_HOST + '/api/system/manage/clues/export?a=0'

            if (this.searchData.followStatus !== '' && this.searchData.followStatus !== '-1') {
                url = url + '&followStatus=' + this.searchData.followStatus
            }
            if (this.searchData.dataSource.length) {
                url = url + '&dataSources=' + this.searchData.dataSource.join(',')
            }
            if (this.searchData.phone !== '') {
                url = url + '&phone=' + this.searchData.phone
            }
            if (this.searchData.customerName !== '') {
                url = url + '&customerName=' + this.searchData.customerName
            }
            if (this.searchData.referrer !== '') {
                url = url + '&referrer=' + this.searchData.referrer
            }
            if (this.searchData.customerType !== '') {
                url = url + '&customerType=' + this.searchData.customerType
            }
            if (this.searchData.time.length) {
                url = url + '&startCreateTime=' + this.searchData.time[0] + '&endCreateTime=' + this.searchData.time[1]
            }
            console.log(url)
            CreateAxiosDownload(url, '线索列表')
            // CreateXMLHttpRequest(url, '线索列表')
        } else if (type === 'sync') {
            this.syncDialog.visible = true
            //设置当前时间
            this.defaultTime[1] = new Date()
        } else if (type === 'detail') {
            this.detailDialog.visible = true
            this.detailData = data
        } else if (type === 'batch') {
            if (this.multiSelectionData.length) {
                this.allocateDialog.visible = true
            } else {
                ElMessage.warning('请选择要分配的数据')
            }
        } else if (type === 'create') {
            this.editDialog.visible = true
        } else if (type === 'download-template') {
            const url = import.meta.env.VITE_HOST + '/api/system/template/download/clueCreate'
            CreateAxiosDownload(url, '线索导入模板')
        } else if (type === 'import') {
            importClues(data[0]).then(res => {
                if (Number(res.data.code) === 200) {
                    ElMessage.success('上传成功')
                    this.getData()
                }
            })
        }
    }
    onMultiSelection = (rows: any) => {
        console.log(rows)
        this.multiSelectionData.length = 0
        rows.forEach((item: any) => {
            this.multiSelectionData.push(item.id)
        })
    }
    //监听弹窗关闭
    onCloseDialog = (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.resetFields()
        this.dialog.visible = false
    }
    //监听弹窗点击确定按钮
    submitForm = async (formEl: FormInstance | undefined) => {
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (valid) {
                console.log('submit!', this.dialogForm)
                const data: clueOperationInterface = {
                    followMsg: this.dialogForm.remark,
                    followStatus: Number(this.dialogForm.followStatus),
                    id: this.dialogForm.id,
                    follower: '管理员'
                }
                clueEdit(data).then(res => {
                    if (Number(res.data.code) === 200) {
                        this.dialog.visible = false
                        this.getData()
                    }
                })
            }
        })
    }
    //监听同步弹窗关闭
    onCloseSyncDialog = () => {
        this.syncDialog.visible = false
        this.getData()
    }
    //监听详情弹出关闭
    onClosedetailDialog() {
        this.detailDialog.visible = false
    }
    //监听分配弹窗关闭
    onCloseAllocateDialog() {
        console.log('close')
        this.allocateDialog.visible = false
        this.getData()
    }
    //监听编辑数据弹窗关闭
    onCloseEditDialog() {
        this.editDialog.visible = false
        setTimeout(() => {
            this.getData()
        }, 500)
    }
}
